/*
 * RevenueSourceDAO.java
 *
 * Created on March 7, 2007, 1:18 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Data;

import java.sql.*;
import java.util.*;
/**
 *
 * @author Danny Beutler
 */
public abstract class RevenueSourceDAO {
    ///////////////////////////////////////
    ///   Singleton pattern
    
//    private static RevenueSourceDAO instance = null;
    
    /** Creates a new instance of revenueSource */
    public RevenueSourceDAO() {
    }
    
//    public static synchronized RevenueSourceDAO getInstance() {
//        if (instance == null) {
//            instance = new RevenueSourceDAO();
//        }
//        return instance;
//    }
    
    
    /////////////////////////////////
    ///   CREATE
    
    //All create Methods were commented out because a RevenueSourceBO is never created
    
//    public RevenueSourceBO create() throws Exception {
//        String id = GUID.generate();
//        RevenueSourceBO revenueSource = new RevenueSourceBO(id);
//        Cache c = Cache.getInstance();
//        c.put(revenueSource.getId(), revenueSource);
//        return revenueSource;
//    }
//
//    public RevenueSourceBO create(String id){
//        RevenueSourceBO revenueSource = new RevenueSourceBO(id);
//        Cache c = Cache.getInstance();
//        c.put(revenueSource.getId(),revenueSource);
//        return revenueSource;
//    }
//
//    private RevenueSourceBO create(ResultSet rs) throws SQLException{
//        RevenueSourceBO revenueSource;
//        revenueSource = new RevenueSourceBO(rs.getString("ID"));
//        //save to the cache
//        Cache.getInstance().put(revenueSource.getId(),revenueSource);
//        revenueSource.setAlreadyInDB(true);
//        revenueSource.setType(rs.getString("Type"));
//
//
//        return revenueSource;
//    }
    
    
    /////////////////////////////////////
    ///   READ
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized RevenueSourceBO read(String id) throws DataException {
        RevenueSourceBO revenueSource;
        Connection conn;
        // check to see if id in the cache
        // if so, return it immediately
        //This was commented out because we don't want it returning until it has populated the values
//        if(Cache.getInstance().containsKey(id)){
//            return (RevenueSourceBO) Cache.getInstance().get(id);
//        }
        
        try {
            
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            
            // call read with a connection (the other read method in this class)
            revenueSource = read(id, conn);
            
            // release the connection
            ConnectionPool.getInstance().release(conn);
            // rollback
            conn.rollback();
        }catch (ConnectionPoolException ex) {
            
            throw new DataException("Unable to communicate with the Database", ex);
            
        }catch (SQLException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        return revenueSource;
    }
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    public RevenueSourceBO read(String id,Connection conn) throws DataException {
        RevenueSourceBO revenueSource=null;
        // check the cache to see if the customer is in the cache
        // if so, return it immediately
        if(Cache.getInstance().containsKey(id)){
            revenueSource = (RevenueSourceBO) Cache.getInstance().get(id);
        }else{
            throw new DataException("Error When Trying to retrieve the RevenueSource from the cache");
        }
        
        try{
            PreparedStatement pstmt =conn.prepareStatement("Select * from \"RevenueSource\" WHERE id=?");
            pstmt.setString(1,id);
            
            ResultSet rs = pstmt.executeQuery();
            // get a rs from an sql SELECT statement
            // if( rs.next()){convert the rs to the member}
            if(rs.next()){
                revenueSource.setDescription(rs.getString("Description"));
                
                // else {handling for no customer with that GUID
            }
        }catch(SQLException e){
            //rollback
            throw new DataException("Could not retrieve record for id=" + id,e);
        }
        //release the connection back to the pool.
        return revenueSource;
    }
    
    /////////////////////////////////////
    ///   READRevenueSourceBO
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public static synchronized RevenueSourceBO readRevenueSource(String id) throws DataException {
        RevenueSourceBO revenueSource;
        Connection conn;
//         check to see if id in the cache
//         if so, return it immediately
        
        if(Cache.getInstance().containsKey(id)){
            return (RevenueSourceBO) Cache.getInstance().get(id);
        }
        
        try {
            
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            
            // call read with a connection (the other read method in this class)
            revenueSource = readRevenueSource(id, conn);
            
            // release the connection
            ConnectionPool.getInstance().release(conn);
            // rollback
            conn.rollback();
        }catch (ConnectionPoolException ex) {
            throw new DataException("Unable to communicate with the Database", ex);
            
        }catch (SQLException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        return revenueSource;
    }
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    public static RevenueSourceBO readRevenueSource(String id,Connection conn) throws DataException {
        RevenueSourceBO revenueSource=null;
        // check the cache to see if the customer is in the cache
        // if so, return it immediately
        
        try{
            PreparedStatement pstmt =conn.prepareStatement("Select * from \"RevenueSource\" WHERE id=?");
            pstmt.setString(1,id);
            
            ResultSet rs = pstmt.executeQuery();
            // get a rs from an sql SELECT statement
            // if( rs.next()){convert the rs to the member}
            if(rs.next()){
                String revenueSourceType = rs.getString("Type");
                RevenueSourceDAO rsDAO = RevenueSourceFactory.getInstance().getDAO(revenueSourceType);
                revenueSource= rsDAO.read(id);
                
                // else {handling for no customer with that GUID
            }
        }catch(SQLException e){
            //rollback
            throw new DataException("Could not retrieve record for id=" + id,e);
        }
        //release the connection back to the pool.
        return revenueSource;
    }
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     */
    public synchronized void save(RevenueSourceBO revenueSource) throws DataException {
        
        try {
            // retrieve a database connection from the pool
            Connection conn=ConnectionPool.getInstance().get();
            // call save with a connection (the other save method in this class)
            save(revenueSource, conn);
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }catch (SQLException e) {
            // rollback
            throw new DataException("Could not save record for id=" + revenueSource.getId(), e);
        }catch (ConnectionPoolException e){
            throw new DataException("Could not retrieve Connection", e);
        }
        
        // release the connection back to the pool
        
    }
    
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CustomerDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     */
    synchronized void save(RevenueSourceBO revenueSource, Connection conn) throws SQLException, DataException {
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (revenueSource.isDirty()) {
            if (revenueSource.isAlreadyInDB()) {
                update(revenueSource, conn);
            }else{
                insert(revenueSource, conn);
            }
            // set the dirty flag to false now that we've saved it
            revenueSource.setDirty(false);
        }
        
        // call save(bo, conn) on any subobjects (like CustomerDAO to MembershipDAO)
        /*This next line was removed because we don't have all of the code to remediate the circulare saves.
         CustomerDAO.getInstance().save(member.getCustomer(),conn);
         **/
        // touch the cache for the object
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(RevenueSourceBO revenueSource,Connection conn) throws SQLException, DataException {
        // do the update statement
        PreparedStatement pstmt =conn.prepareStatement("UPDATE \"RevenueSource\" SET \"Description\" = ?," +
                " \"Price\" = ?," +
                " WHERE \"ID\" = ?");
        
        
        pstmt.setString(1,revenueSource.getDescription());
        pstmt.setDouble(2,revenueSource.getPrice());
        pstmt.setString(3,revenueSource.getId());
        
        pstmt.executeUpdate();
        
        //Do the membership interests insertion
        
        
        System.out.println("revenueSourceUpdateSuccessful");
    }
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(RevenueSourceBO revenueSource,Connection conn) throws SQLException, DataException {
        // do the insert SQL statement
        PreparedStatement pstmt =conn.prepareStatement("INSERT INTO \"RevenueSource\" VALUES (?,?,?,?)");
        pstmt.setString(1,revenueSource.getId());
        pstmt.setString(2,revenueSource.getDescription());
        pstmt.setDouble(3,revenueSource.getPrice());
        pstmt.setString(4,revenueSource.getClass().getName());
        
        pstmt.executeUpdate();
        System.out.println("revenueSourceInsertSucessful");
        
        //Do the membership interests insertion
        // tell the object that it's now in the db (so we call update next time not insert)
        revenueSource.setAlreadyInDB(true);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    
    // We have decided not to support delete because we would like the revenueSources to stay in the database for data archiving.
    
    //////////////////////////////
    ///  SEARCH methods
    
    
}
